<template>
  <a-modal
    width="800px"
    v-model:visible="visible"
    title="站点签发证书"
    @before-ok="onOk"
    ok-text="续签证书"
    :mask-closable="false"
  >
    <a-descriptions class="mb-20" :column="2" :label-style="{ fontWeight: 'bold' }">
      <a-descriptions-item label="证书分类">
        <a-tag>{{ form.ssl.certData.issuerO }}</a-tag>
      </a-descriptions-item>
      <a-descriptions-item label="证书品牌">
        <a-tag>{{ form.ssl.certData.issuer }}</a-tag>
      </a-descriptions-item>
      <a-descriptions-item label="认证域名">
        <a-tag>{{ form.ssl.certData.subject }}</a-tag>
      </a-descriptions-item>
      <a-descriptions-item label="到期时间">
        <a-tag>{{ form.ssl.expireTime }}</a-tag>
      </a-descriptions-item>
    </a-descriptions>
    <div class="flex">
      <div class="flex-1 flex-col">
        <span class="text999 mb-6">秘钥（KEY）</span>
        <a-textarea placeholder="请输入秘钥" v-model="form.ssl.key" :auto-size="{ maxRows: 16 }"></a-textarea>
      </div>
      <div class="flex-1 flex-col ml-m">
        <span class="text999 mb-6">证书（PEM格式）</span>
        <a-textarea placeholder="请输入证书" v-model="form.ssl.csr" :auto-size="{ maxRows: 16 }"></a-textarea>
      </div>
    </div>
  </a-modal>
</template>

<script setup>
import { applyCertApi } from '@/apis'
import { Message } from '@arco-design/web-vue'
import { reAssign } from '@/utils/common'

const emit = defineEmits(['getTableData'])

const visible = ref(false)
const formRef = ref()

const form = reactive({
  id: undefined,
  ssl: {
    id: undefined, //ID 存在为编辑
    siteId: undefined, //站点ID
    accountId: undefined, //账户ID
    domain: [
      {
        name: undefined
      }
    ],
    key: undefined,
    csr: undefined,
    certData: {
      issuer: undefined,
      issuerO: undefined,
      notAfter: undefined,
      notBefore: undefined,
      dns: [],
      subject: undefined,
      endtime: undefined,
      id: undefined,
      ps: undefined
    },
    tlsVersions: { TLSv1: undefined, 'TLSv1.1': undefined, 'TLSv1.2': undefined, 'TLSv1.3': undefined },
    type: undefined,
    index: undefined,
    expireTime: undefined,
    createdAt: undefined,
    updatedAt: undefined,
    days: undefined
  }
})

// 打开编辑框并回显表单值
const addOrEdit = (item) => {
  reAssign(form, item)
  console.log(item, form)
  item && formRef.value?.validate()
  visible.value = true
}

// 点击确认添加/编辑
const onOk = async () => {
  if (!form.ssl.key) {
    Message.error('请填写KEY')
    return false
  }
  if (!form.ssl.csr) {
    Message.error('请填写证书')
    return false
  }
  await applyCertApi({ id: form.id })
  Message.success('操作成功')
  emit('getTableData')
  return true
}

provide('formRef', formRef)
defineExpose({ addOrEdit })
</script>
